import { pool } from '../config/db.js'

// 添加评论
export const addComment = async (req, res) => {
  try {
    const { pageId, content } = req.body
    const userId = req.user.id

    if (!pageId || !content) {
      return res.status(400).json({ message: '页面ID和评论内容都是必填的' })
    }

    const [result] = await pool.execute(
      'INSERT INTO comments (user_id, page_id, content) VALUES (?, ?, ?)',
      [userId, pageId, content],
    )

    // 获取刚添加的评论
    const [comments] = await pool.execute(
      `SELECT c.id, c.content, c.created_at, u.username
       FROM comments c
       JOIN users u ON c.user_id = u.id
       WHERE c.id = ?`,
      [result.insertId],
    )

    res.status(201).json({
      message: '评论成功',
      comment: comments[0],
    })
  } catch (error) {
    console.error('添加评论失败:', error)
    res.status(500).json({ message: '添加评论失败' })
  }
}

// 获取页面评论
export const getComments = async (req, res) => {
  try {
    const { pageId } = req.params

    if (!pageId) {
      return res.status(400).json({ message: '页面ID是必填的' })
    }

    const [comments] = await pool.execute(
      `SELECT c.id, c.content, c.created_at, c.user_id, u.username
       FROM comments c
       JOIN users u ON c.user_id = u.id
       WHERE c.page_id = ?
       ORDER BY c.created_at DESC`,
      [pageId],
    )

    res.status(200).json({ comments })
  } catch (error) {
    console.error('获取评论失败:', error)
    res.status(500).json({ message: '获取评论失败' })
  }
}

// 点赞页面
export const likePost = async (req, res) => {
  try {
    const { pageId } = req.body
    const userId = req.user.id

    if (!pageId) {
      return res.status(400).json({ message: '页面ID是必填的' })
    }

    // 检查是否已经点赞
    const [existingLikes] = await pool.execute(
      'SELECT * FROM likes WHERE user_id = ? AND page_id = ?',
      [userId, pageId],
    )

    // 如果已经点赞，则取消点赞
    if (existingLikes.length > 0) {
      await pool.execute('DELETE FROM likes WHERE user_id = ? AND page_id = ?', [userId, pageId])

      // 获取当前点赞数
      const [likesCount] = await pool.execute(
        'SELECT COUNT(*) as count FROM likes WHERE page_id = ?',
        [pageId],
      )

      return res.status(200).json({
        message: '取消点赞成功',
        liked: false,
        count: likesCount[0].count,
      })
    }

    // 如果未点赞，则添加点赞
    await pool.execute('INSERT INTO likes (user_id, page_id) VALUES (?, ?)', [userId, pageId])

    // 获取当前点赞数
    const [likesCount] = await pool.execute(
      'SELECT COUNT(*) as count FROM likes WHERE page_id = ?',
      [pageId],
    )

    res.status(201).json({
      message: '点赞成功',
      liked: true,
      count: likesCount[0].count,
    })
  } catch (error) {
    console.error('点赞操作失败:', error)
    res.status(500).json({ message: '点赞操作失败' })
  }
}

// 检查用户是否已点赞页面
export const checkLikeStatus = async (req, res) => {
  try {
    const { pageId } = req.params

    if (!pageId) {
      return res.status(400).json({ message: '页面ID是必填的' })
    }

    // 获取点赞数
    const [likesCount] = await pool.execute(
      'SELECT COUNT(*) as count FROM likes WHERE page_id = ?',
      [pageId],
    )

    // 如果用户已登录，检查是否已点赞
    if (req.user) {
      const userId = req.user.id
      // 检查是否已经点赞
      const [existingLikes] = await pool.execute(
        'SELECT * FROM likes WHERE user_id = ? AND page_id = ?',
        [userId, pageId],
      )

      return res.status(200).json({
        liked: existingLikes.length > 0,
        count: likesCount[0].count,
      })
    }

    // 未登录用户只返回点赞总数
    res.status(200).json({
      liked: false,
      count: likesCount[0].count,
    })
  } catch (error) {
    console.error('检查点赞状态失败:', error)
    res.status(500).json({ message: '检查点赞状态失败' })
  }
}

// 分享页面
export const sharePage = async (req, res) => {
  try {
    const { pageId } = req.body
    const userId = req.user.id

    if (!pageId) {
      return res.status(400).json({ message: '页面ID是必填的' })
    }

    // 记录分享信息
    await pool.execute('INSERT INTO shares (user_id, page_id) VALUES (?, ?)', [userId, pageId])

    // 获取当前分享数
    const [sharesCount] = await pool.execute(
      'SELECT COUNT(*) as count FROM shares WHERE page_id = ?',
      [pageId],
    )

    res.status(201).json({
      message: '分享成功',
      sharesCount: sharesCount[0].count,
    })
  } catch (error) {
    console.error('分享失败:', error)
    res.status(500).json({ message: '分享失败' })
  }
}

// 获取页面分享数
export const getSharesCount = async (req, res) => {
  try {
    const { pageId } = req.params

    if (!pageId) {
      return res.status(400).json({ message: '页面ID是必填的' })
    }

    // 获取分享数
    const [sharesCount] = await pool.execute(
      'SELECT COUNT(*) as count FROM shares WHERE page_id = ?',
      [pageId],
    )

    res.status(200).json({
      sharesCount: sharesCount[0].count,
    })
  } catch (error) {
    console.error('获取分享数失败:', error)
    res.status(500).json({ message: '获取分享数失败' })
  }
}

// 删除评论
export const deleteComment = async (req, res) => {
  try {
    const { id } = req.params
    const userId = req.user.id

    if (!id) {
      return res.status(400).json({ message: '评论ID是必填的' })
    }

    // 检查评论是否存在
    const [comments] = await pool.execute('SELECT * FROM comments WHERE id = ?', [id])

    if (comments.length === 0) {
      return res.status(404).json({ message: '评论不存在' })
    }

    // 检查是否是管理员或评论作者
    // 这里简化处理，实际应用中应该有管理员角色检查
    const comment = comments[0]
    if (comment.user_id !== userId) {
      // 检查是否是管理员的逻辑应该在这里
      // 暂时允许任何登录用户删除评论
    }

    // 删除评论
    await pool.execute('DELETE FROM comments WHERE id = ?', [id])

    res.status(200).json({ message: '评论删除成功' })
  } catch (error) {
    console.error('删除评论失败:', error)
    res.status(500).json({ message: '删除评论失败' })
  }
}

// 获取页面交互统计数据（用于后台管理）
export const getInteractionStats = async (req, res) => {
  try {
    console.log('获取交互统计数据请求，headers:', req.headers)

    // 获取所有页面的交互数据（包括只有评论或只有分享的页面）
    const [stats] = await pool.execute(`
      SELECT
        all_pages.page_id,
        COUNT(DISTINCT c.id) as comments_count,
        COUNT(DISTINCT l.id) as likes_count,
        COUNT(DISTINCT s.id) as shares_count
      FROM (
        SELECT page_id FROM comments
        UNION
        SELECT page_id FROM likes
        UNION
        SELECT page_id FROM shares
      ) as all_pages
      LEFT JOIN comments c ON all_pages.page_id = c.page_id
      LEFT JOIN likes l ON all_pages.page_id = l.page_id
      LEFT JOIN shares s ON all_pages.page_id = s.page_id
      GROUP BY all_pages.page_id
    `)

    console.log('交互统计数据:', stats)
    res.status(200).json({ stats })
  } catch (error) {
    console.error('获取互动统计数据失败:', error)
    res.status(500).json({ message: '获取互动统计数据失败' })
  }
}
